//index.js
const app = getApp()
import config from '../../utils/config'
import utils from '../../utils/util'
let Charts = require('../../utils/wxcharts-min.js');
import {
  statisticsModel
} from '../../models/statistics';
const statistics = new statisticsModel();
import {
  productModel
} from '../../models/product';
const product = new productModel();
import Dialog from '../../vant/dialog/dialog';
Page({
  data: {
    nvabarData: {
      showCapsule: 0, //是否显示左上角图标   1表示显示    0表示不显示
      title: '首页',
      //  导航栏 中间的标题
    },
    config: config,
    fLoad: false,

    active: 0, // 0完成金额,1配送订单,2确认订单
    canvasTemImg1: '',
    canvasTemImg2: '',
    canvasTemImg3: '',
    completeMoney: 0, // 已完成金额
    payedMoney: 0, // 已结账金额
    notPayMoney: 0, // 待结账金额
    sendOrderCount: 0, // 已配送订单
    notSendOrderCount: 0, // 待配送订单
    notConfirmOrderCount: 0, // 待确认订单
    otherOrderCount: 0, // 其他
    statisticsData: '',
    
    allPage: 0, // 所有页数
    page: 1, // 第几页
    endFlag: false, // 是否到最后
    goodsList: [], // 商品列表
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    this.data.fLoad = true
    this.getAuth() // 判断是否登录
    
  },
  // 判断是否登录
  getAuth() {
    var _this = this
    wx.request({
      url: config.projectUrl + 'supplier/app/supplier/currentSupplierInfo',
      method: 'get',
      header: {
        'authentication': wx.getStorageSync('authentication')
      },
      success: function (res) {
        if(res.data.code == '402'){
          Dialog.confirm({
            title: '提示',
            message: '您还未登录，请先登录再进行操作',
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          }).then(() => {
            wx.reLaunch({
              url: '/pages/login/login'
            })
          }).catch(() => {
            // on cancel
          });
        }else{
          _this.getStatistics() // 数据统计
          _this.getProduct() // 报价商品 
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(!this.data.fLoad){ // 不是第一次进入这个页面
      this.data.active = 0, // 0完成金额,1配送订单,2确认订单
      this.data.canvasTemImg1 = '',
      this.data.canvasTemImg2 = '',
      this.data.canvasTemImg3 = '',
      this.data.completeMoney = 0, // 已完成金额
      this.data.payedMoney = 0, // 已结账金额
      this.data.notPayMoney = 0, // 待结账金额
      this.data.sendOrderCount = 0, // 已配送订单
      this.data.notSendOrderCount = 0, // 待配送订单
      this.data.notConfirmOrderCount = 0, // 待确认订单
      this.data.otherOrderCount = 0, // 其他
      // this.data.allPage = 0, // 所有页数
      // this.data.page = 1, // 第几页
      // this.data.endFlag = false, // 是否到最后
      // this.data.goodsList = [], // 商品列表
      
      this.setData({
        allPage: 0,
        page: 1,
        endFlag: false,
        goodsList: []
      })
      // 判断是否登录
      this.getAuth()
    }
    this.data.fLoad = false
  },
  // 数据统计
  getStatistics(){
    statistics.statisticsList({}, res => {
      this.setData({
        statisticsData: res.data
      })
      this.cartFun1(res.data) // 账单金额图表
      this.cartFun2(res.data) // 订单配送图表
      this.cartFun3(res.data) // 待确认订单图表
    })
  },
  // 账单金额图表
  cartFun1(data){
    var _this = this
    var sum = data.supplierOrderBillCountVo.completeMoney + data.supplierOrderBillCountVo.payedMoney + data.supplierOrderBillCountVo.notPayMoney
    if(sum != 0){
      var completeMoney = (data.supplierOrderBillCountVo.completeMoney/sum*100).toFixed(0)
      var payedMoney = (data.supplierOrderBillCountVo.payedMoney/sum*100).toFixed(0)
      var notPayMoney = 100-completeMoney-payedMoney
      this.setData({
        completeMoney,
        payedMoney,
        notPayMoney
      })
      let chart = new Charts({
        animation: false,
        canvasId: 'canvas1',
        type: 'ring',
        extra: {
          ringWidth: 30,//圆环的宽度
        },
        series: [{
          name: '已完成金额',
          data: data.supplierOrderBillCountVo.completeMoney,
          color: '#3FDA93',
          stroke: false
        }, {
          name: '已结账金额',
          data: data.supplierOrderBillCountVo.payedMoney,
          color: '#2FBEE4',
          stroke: false
        }, {
          name: '待结账金额',
          data: data.supplierOrderBillCountVo.notPayMoney,
          color: '#F18C58',
          stroke: false
        }],
        disablePieStroke: true,
        width: 170,
        height: 170,
        dataLabel: false,
        legend: false,
        padding: 0,
        background: '#ffffff'
      });
      chart.addEventListener('renderComplete', () => {
        setTimeout(function(){
          _this.draw1()
        },300)
      });
    }
  },
  // 账单金额图表生成图片
  draw1(){
    var _this = this
    wx.canvasToTempFilePath({
      canvasId:'canvas1',
      quality: 1,
      success: res => {
        setTimeout(function(){
          _this.setData({
            canvasTemImg1: res.tempFilePath
          })
        },200)
      },
      fail: res => {
        console.log(res)
      }
    },this)

  },
  // 订单配送图表
  cartFun2(data){
    var sum = data.supplierOrderCountVo.sendOrderCount + data.supplierOrderCountVo.notSendOrderCount
    if(sum != 0){
      var sendOrderCount = (data.supplierOrderCountVo.sendOrderCount/sum*100).toFixed(0)
      var notSendOrderCount = 100-sendOrderCount
      this.setData({
        sendOrderCount,
        notSendOrderCount
      })
      new Charts({
        animation: true,
        canvasId: 'canvas2',
        type: 'ring',
        extra: {
          ringWidth: 30,//圆环的宽度
        },
        series: [{
          name: '已配送订单',
          data: data.supplierOrderCountVo.sendOrderCount,
          color: '#2FBEE4',
          stroke: false
        }, {
          name: '待配送订单',
          data: data.supplierOrderCountVo.notSendOrderCount,
          color: '#F18C58',
          stroke: false
        }],
        disablePieStroke: true,
        width: 170,
        height: 170,
        dataLabel: false,
        legend: false,
        padding: 0,
        background: '#ffffff'
      });
    }
  },
  // 订单配送图表生成图片
  draw2(){
    var _this = this
    wx.canvasToTempFilePath({
      canvasId:'canvas2',
      quality: 1,
      success: res => {
        console.log(res.tempFilePath)
        _this.setData({
          canvasTemImg2: res.tempFilePath
        })
      },
      fail: res => {
        console.log(res)
      }
    },this)

  },
  // 待确认订单图表
  cartFun3(data){
    var _this = this
    var sum = data.supplierOrderCountVo.notConfirmOrderCount + data.supplierOrderCountVo.otherOrderCount
    if(sum != 0){
      var notConfirmOrderCount = (data.supplierOrderCountVo.notConfirmOrderCount/sum*100).toFixed(0)
      var otherOrderCount = 100-notConfirmOrderCount
      this.setData({
        notConfirmOrderCount,
        otherOrderCount
      })
      new Charts({
        animation: true,
        canvasId: 'canvas3',
        type: 'ring',
        extra: {
          ringWidth: 30,//圆环的宽度
        },
        series: [{
          name: '待确认订单',
          data: data.supplierOrderCountVo.notConfirmOrderCount,
          color: '#2FBEE4',
          stroke: false
        }, {
          name: '其他',
          data: data.supplierOrderCountVo.otherOrderCount,
          color: '#F18C58',
          stroke: false
        }],
        disablePieStroke: true,
        width: 170,
        height: 170,
        dataLabel: false,
        legend: false,
        padding: 0,
        background: '#ffffff'
      });
    }
  },
  // 待确认订单图表生成图片
  draw3(){
    var _this = this
    wx.canvasToTempFilePath({
      canvasId:'canvas3',
      quality: 1,
      success: res => {
        _this.setData({
          canvasTemImg3: res.tempFilePath
        })
      },
      fail: res => {
        console.log(res)
      }
    },this)

  },
  // 点击切换标签
  onTab: utils.throttle(function (e) {
    var _this = this
    var index = e.currentTarget.dataset.index
    index = Number(index)
    this.setData({
      active: index
    })
    switch(index){
      case 0: // 账单金额
        if(!this.data.canvasTemImg1&&!(this.data.completeMoney==0&&this.data.payedMoney==0&&this.data.notPayMoney==0)){
          setTimeout(function(){
            _this.draw1()
          },500)
        }
        break;
      case 1: // 订单配送
        if(!this.data.canvasTemImg2&&!(this.data.sendOrderCount==0&&this.data.notSendOrderCount==0)){
          setTimeout(function(){
            _this.draw2()
          },500)
        }
        break;
      case 2: // 待确认订单
        if(!this.data.canvasTemImg3&&!(this.data.notConfirmOrderCount==0&&this.data.otherOrderCount==0)){
          setTimeout(function(){
            _this.draw3()
          },500)
        }
        break;
    }
  },500),
  // 报价商品
  getProduct(showLoading=true){
    product.listQuotePage({
      page: this.data.page,
      limit: 10,
    }, res => {
      if (res.data.list.length > 0) {
        var page = this.data.page;
        var allPage = res.data.allPage;
        var endFlag = false;
        if (page == allPage) {
          endFlag = true;
        } else {
          page += 1;
        }
        var goodsList = this.data.goodsList
        goodsList = goodsList.concat(res.data.list)
        this.setData({
          goodsList: goodsList,
          page: page,
          allPage: allPage,
          endFlag: endFlag
        })
      }
    },showLoading)
  },
  // 报价
  onOffer: utils.throttle(function (e) {
    var id = e.currentTarget.dataset.productid
    var quote = e.currentTarget.dataset.quote
    var shelf = e.currentTarget.dataset.shelf
    var index = e.currentTarget.dataset.index
    // if(quote!=1&&shelf==1){
    //   utils.msg('请先下架该商品，再进行修改')
    //   return
    // }
    wx.navigateTo({
      url: '/pages/offerFast/offer/offer?id='+ id +'&quote='+ quote +'&type=1&pageindex=' + index,
    })
  }),

  // 商品详情
  onDetail: utils.throttle(function (e) {
    var id = e.currentTarget.dataset.productid
    wx.navigateTo({
      url: '/pages/index/commodityInfo/commodityInfo?id=' + id,
    })
  }),
  
  // 账单列表
  onBill: utils.throttle(function (e) {
    wx.navigateTo({
      url: '/pages/personal/bill/bill',
    })
  }),

  // 订单列表
  onOrder: utils.throttle(function (e) {
    wx.switchTab({
      url: '/pages/order/order'
    })
  }),

  // 下架
  onDown: utils.throttle(function (e) {
    var _this = this
    var id = e.currentTarget.dataset.productid
    Dialog.confirm({
      message: '是否确认下架？'
    }).then(() => {
      // on confirm
      product.shelfDown({
        productId: id
      },res => {
        var goodsList = _this.data.goodsList
        var index = e.currentTarget.dataset.index
        goodsList[index].shelfStatus = 0
        _this.setData({
          goodsList: goodsList
        })
        utils.msg('操作成功')
      })
    }).catch(() => {
      // on cancel
    });
  }),
  // 上架
  onUp: utils.throttle(function (e) {
    var _this = this
    var id = e.currentTarget.dataset.productid
    Dialog.confirm({
      message: '是否确认上架？'
    }).then(() => {
      // on confirm
      product.shelfUp({
        productId: id
      },res => {
        var goodsList = _this.data.goodsList
        var index = e.currentTarget.dataset.index
        if(res.data == 0){
          goodsList[index].reviewStatus = 0
        }else{
          goodsList[index].shelfStatus = 1
        }
        _this.setData({
          goodsList: goodsList
        })
        utils.msg('操作成功')
      })
    }).catch(() => {
      // on cancel
    });
    
  }),
  
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.data.active = 0, // 0完成金额,1配送订单,2确认订单
    this.data.canvasTemImg1 = '',
    this.data.canvasTemImg2 = '',
    this.data.canvasTemImg3 = '',
    this.data.completeMoney = 0, // 已完成金额
    this.data.payedMoney = 0, // 已结账金额
    this.data.notPayMoney = 0, // 待结账金额
    this.data.sendOrderCount = 0, // 已配送订单
    this.data.notSendOrderCount = 0, // 待配送订单
    this.data.notConfirmOrderCount = 0, // 待确认订单
    this.data.otherOrderCount = 0, // 其他
    this.data.allPage = 0, // 所有页数
    this.data.page = 1, // 第几页
    this.data.endFlag = false, // 是否到最后
    this.data.goodsList = [], // 商品列表
    this.getStatistics() // 数据统计
    this.getProduct() // 报价商品 
    //模拟加载 		
    setTimeout(function () {
      // complete 			
      wx.hideNavigationBarLoading() //完成停止加载 			
      wx.stopPullDownRefresh() //停止下拉刷新 		

    }, 1500);

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log('bottom');
    if (this.data.endFlag) {
      utils.msg('已是最后了');
      return;
    } else {
      this.getProduct();

    }
  },

})
